<?php

namespace App\Http\Controllers\Admin;

use App\Classes\EasyTree;
use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\AdminMenu;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Lang;

class MenuController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'parentID'      => 'required',
        'name'          => 'required',
        'listOrder'     => 'required'
    ];
    /**
     * 目录管理
     * @return $this
     */
    public function getIndex()
    {
        $tree = Cache::remember('admin_tree', 30, function()
        {
            //整理目录
            $menu = $this->menu;

            foreach ($menu as $k=>$v)
            {
                $menu[$k]->cname        =   Lang::has('admin-menu.name.'.$v->name) ? Lang::get('admin-menu.name.'.$v->name) : $v->name;
                $menu[$k]->checked      =   $v->display == 1 ? 'checked' : 'checked-false';
                $menu[$k]->addChildUrl  =   action('Admin\MenuController@getAdd', ['parentID' => $v->id]);
                $menu[$k]->editUrl      =   action('Admin\MenuController@getEdit', ['id' => $v->id]);
                $menu[$k]->deleteUrl    =   action('Admin\MenuController@getDel', ['id' => $v->id]);
            }
            //设置模板
            $template = "<tr>
                            <td class='text-center border-right'><input type='text' name='listorder[\$v->id]' value='\$v->listOrder' style='width:40px;'></td>
                            <td class='text-center'><i class='\$v->icon'></i></td>
                            <td>\$spacer \$v->cname</td>
                            <td class='text-center'><input class='switch' type='checkbox' data-id='\$v->id' name='show[\$v->id]' \$v->checked data-on-text='".getLang('Tips', 'showON')."' data-off-text='".getLang('Tips', 'showOFF')."' data-label-width='0' data-on-color='success' data-off-color='danger' data-size='mini'></td>
                            <td>\$v->controller</td>
                            <td class='text-center'>
                                <a href='\$v->addChildUrl' class='btn btn-success btn-xs' data-toggle='tooltip' data-placement='top' data-original-title='".getLang('Tips', 'createSonMenu')."'><i class='fa fa-plus'></i></a>
                                <a href='\$v->editUrl' class='btn btn-primary btn-xs' data-toggle='tooltip' data-placement='top' data-original-title='".getLang('Tips', 'edit')."'><i class='fa fa-pencil'></i></a>
                                <button type='button' data-url='\$v->deleteUrl' data-tips='".getLang('Tips', 'isDelete')." : \$v->cname' class='btn btn-danger btn-xs delete-table' data-toggle='tooltip' data-placement='top' data-original-title='".getLang('Tips', 'delete')."'><i class='fa fa-times'></i></button>
                            </td>
                     </tr>";
            //创建目录树HTML
            $tree = new EasyTree($menu);
            return $tree->setTemplate($template)->getTree();
        });

        return view('admin.menu')->with(['tree' => $tree]);
    }

    /**
     * 排序
     * @param Request $request
     * @return $this
     */
    public function postIndex(Request $request)
    {
        //初始化
        $listOrder = [];
        $num = 0;
        $listOrder = $request->input('listorder');
        //格式化$show内容并跟新数据库
        foreach ($listOrder as $key=>$v) {
            $thisMenu = AdminMenu::find($key);
            if ($thisMenu->listOrder==$v)
                continue;
            $thisMenu->listorder = $v;
            if ($thisMenu->update())
                $num += 1;
        }
        if ($num>0)
        {
            Cache::forget('admin_tree');
            return ShowMsg('success', getLang('Tips', 'updateSuccess'),'',1);
        }
        return ShowMsg('warning', getLang('Tips', 'updateNone'),'',1);
    }

    /**
     * 获取添加和修改目录里的选项目录
     * @param $parentID
     * @return string
     */
    private function getSelect($parentID)
    {
        $tree = Cache::remember('admin_tree_select', 30, function() use($parentID)
        {
            $menu = $this->menu;
            foreach ($menu as $k=>$v)
            {
                $menu[$k]->cname    =   Lang::has('admin-menu.name.'.$v->name) ? Lang::get('admin-menu.name.'.$v->name) : $v->name;
                $menu[$k]->selected = '';
                if ($parentID == $v->id)
                {
                    $menu[$k]->selected = 'selected';
                }
            }
            $template = "<option value='\$v->id' \$v->selected>\$spacer \$v->cname</option>";
            $tree = new EasyTree($menu);

            return $tree->setTemplate($template)->getTree();
        });
        return $tree;
    }

    /**
     * 添加目录
     * @param int $parentID
     * @return $this
     */
    public function getAdd($parentID = 0)
    {
        //获取栏目列表
        $tree = $this->getSelect($parentID);

        return view('admin.menu-add')->with(['tree' => $tree]);
    }
    public function postAdd(Request $request)
    {
        //验证
        $verifyMsg = $this->verification($request->input(), $request->has('controller') ? ['controller' => 'unique:admin_menu'] : []);
        if ($verifyMsg)
        {
            return redirect()->action(
                'Admin\MenuController@getAdd',['parentID' => $request->input('parentID') ? $request->input('parentID') : '']
            )->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        $request->merge(['display' => $request->has('display') ? 1 : 0]);
        //Create
        if (AdminMenu::create($request->input()))
        {
            //setLog
            $this->setLog('create', NULL, json_encode($request->except('_token')));

            Cache::forget('admin_tree');
            Cache::forget('admin_tree_select');
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\MenuController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\MenuController@getIndex'), 1);
    }

    /**
     * 修改
     * @param $id
     * @return $this
     */
    public function getEdit($id)
    {
        //获取目录信息
        $adminMenu = AdminMenu::find($id);
        if (empty($adminMenu))
            return redirect()->back();
        //获取栏目列表
        $tree = $this->getSelect($adminMenu->parentID);

        return view('admin.menu-edit')->with(['tree' => $tree, 'adminMenu' => $adminMenu]);
    }
    public function postEdit(Request $request, $id)
    {
        //验证
        $verifyMsg = $this->verification($request->input(), $request->has('controller') ? ['controller' => 'unique:admin_menu,controller,'.$id] : []);
        if ($verifyMsg)
        {
            return redirect()->action(
                'Admin\MenuController@getAdd',['parentID' => $request->input('parentID') ? $request->input('parentID') : '']
            )->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        $request->merge(['display' => $request->has('display') ? 1 : 0]);

        //修改前的值
        $origin = AdminMenu::find($id)->toArray();
        //Update
        if (AdminMenu::where('id', $id)->update($request->except('_token')))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($request->except('_token')));

            Cache::forget('admin_tree');
            Cache::forget('admin_tree_select');
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\MenuController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\MenuController@getEdit', ['id' => $id]), 1);
    }

    /**
     * 删除
     * @param $id
     * @return $this
     */
    public function getDel($id)
    {
        //获取目录
        $menu = AdminMenu::all()->keyBy('id');
        //获得自身和子目录集合
        $child = new EasyTree($menu);
        $child = $child->getContinue($id);
        $array = [(int)$id];
        if ($child)
        {
            $array = array_merge($array, $child);
        }
        //获取原值
        $origin = AdminMenu::whereIn('id', $array)->get()->toArray();

        if (AdminMenu::destroy($array))
        {
            //setLog
            $this->setLog('delete', json_encode($origin));

            Cache::forget('admin_tree');
            Cache::forget('admin_tree_select');
            return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * Ajax是否显示
     * @param Request $request
     * @return string
     */
    public function postDisplay(Request $request)
    {

        $menu = AdminMenu::find($request->input('id'));
        if(!empty($menu))
        {
            $origin = $menu->toArray();
            $menu->display = $request->input('display');
            if ($menu->save())
            {
                //setLog
                $this->setLog('show', json_encode($origin), json_encode($request->except('_token')));
                Cache::forget('admin_tree');
                Cache::forget('admin_tree_select');
                return json_encode([
                    'code'      =>  1,
                    'message'   =>  getLang('Tips', 'updateSuccess')
                ]);
            }
        }
        return json_encode([
            'code'      =>  0,
            'message'   =>  getLang('Tips', 'updateFail')
        ]);
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'menu.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'menu.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'menu.delete',
                    'type'  =>  'Delete'
                ];
                break;
            case 'show':
                $event = [
                    'msg'   =>  'menu.show',
                    'type'  =>  'Update'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
